package com.cqc.jdk8.Jutil.concurrent;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author cui
 * @date 2024/6/15 23:10
 * @description
 **/
public class ExecutorServiceTest {
    /**
     * 并行执行任务
     */
    public static void main(String[] args) {
        System.out.println("###开始  " + DateFormat.getDateTimeInstance().format(new Date()));
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Callable<String>> tasks = new ArrayList<>();
        tasks.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String s = "###任务1  " + DateFormat.getDateTimeInstance().format(new Date());
                System.out.println(s);
                return s;
            }
        });
        tasks.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String s = "###任务2  " + DateFormat.getDateTimeInstance().format(new Date());
                System.out.println(s);
                return s;
            }
        });
        tasks.add(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String s = "###任务3  " + DateFormat.getDateTimeInstance().format(new Date());
            System.out.println(s);
            return s;
        });
        try {
            List<Future<String>> futureList = executorService.invokeAll(tasks, 5, TimeUnit.SECONDS);
            for (Future<String> future : futureList) {
                // 获取线程执行结果
                try {
                    String result = future.get();
                    System.out.println("result=" + result);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //关闭线程池
        executorService.shutdown();
    }
}
